<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>websocket</title>
    <!--socket-->
    <script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
    <!--vue-->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!--elementUI-->
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!--axios-->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
<div id="app">
    <div id="nave">
        <span style="position: absolute;padding-top: 13px;right: 45%;font-size: 20px;">{{receiveUser}}</span>
        <span style="position: absolute;padding-top: 16px;right: 8%;font-size: 16px;font-weight: bold;">当前用户：</span>
        <span style="position: absolute;padding-top: 16px;right: 2%;font-size: 16px;font-weight: bold;">{{sendUser}}</span>
        <input id="username" th:value="${username}" style="display: none;"/><!--隐藏域-->

    </div>
    <div id="side">
        <el-menu style="height: 100%"
                 default-active="all"
                 class="el-menu-vertical-demo"
                 background-color="#545c64"
                 text-color="#fff"
                 active-text-color="#ffd04b">

            <el-menu-item v-for="(item,i) in navList" :key="i" :index="item.name" @click="changeReceiver(item.navItem)">
                {{ item.navItem }}
            </el-menu-item>
        </el-menu>
    </div>
    <div id="chat">
        <div id="receive" style="text-align: left;">
            <el-divider content-position="center">{{time}}</el-divider>
            <table id="receiveTable" style="height: 100%;width: 99%;">
                <tbody id="receiveTbody">

                </tbody>
            </table>
        </div>
        <div id="send">
            <el-input
                    type="textarea"
                    :rows="9"
                    placeholder="请输入内容"
                    v-model="text">
            </el-input>
            <!--            <el-button type="info" plain style="position: absolute;right: 10px;bottom: 10px;">发送</el-button>-->
            <el-dropdown split-button type="info" @click="send" style="position: absolute;right: 10px;bottom: 10px;">
                发送
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>发送图片</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>

        </div>
    </div>
</div>

</body>


<script>
    new Vue({
        el: '#app',
        data: function () {
            return {
                text:'',
                remarks:'',
                webSocket:'',
                navList: [
                    {name: 'all', navItem: '所有人'},
                   /* {name: 'Jack', navItem: 'Jack'},
                    {name: 'Rose', navItem: 'Rose'},
                    {name: 'Tom', navItem: 'Tom'},*/
                ],
                receiveUser:'所有人',
                sendUser:'sendUser',
                time:'',
            }
        },
        mounted(){
            this.sendUser=document.getElementById("username").value//初始化send用户名
            this.time=new Date().toLocaleString()//当前时间

            var self=this

            //判断当前浏览器是否支持WebSocket
            if ("WebSocket" in window) {
                this.webSocket = new WebSocket("ws://localhost:8888/websocket/" + this.sendUser);
                var webSocket=this.webSocket

                //连通之后的回调事件
                webSocket.onopen = function () {
                    //webSocket.send( document.getElementById('username').value+"已经上线了");
                    console.log("已经连通了websocket");
                    self.setHint("已经连通了websocket");
                };

                //接收后台服务端的消息
                webSocket.onmessage = function (evt) {
                    // console.log(evt);

                    var received_msg = evt.data;
                    console.log("数据已接收:" + received_msg);
                    var obj = JSON.parse(received_msg);
                    // console.log(obj);

                    console.log("消息类型:" + obj.messageType);
                    //1代表上线 2代表下线 3代表在线名单 4代表普通消息
                    if (obj.messageType == 1) {
                        //把名称放入到侧边栏
                        var onlineName = obj.username;
                        self.navList.push({name:onlineName,navItem:onlineName})
                        self.setHint(onlineName + "上线了");
                    } else if (obj.messageType == 2) {
                        self.navList=[
                            {name:'all',navItem: '所有人'},
                        ];
                        var onlineName = obj.onlineUsers;
                        var offlineName = obj.username;
                        for (var i = 0; i < onlineName.length; i++) {
                            if (!(onlineName[i] == self.sendUser)) {
                                self.navList.push({name:onlineName[i],navItem:onlineName[i]})
                            }
                        }
                        if(offlineName==self.receiveUser){//判断接收用户是否下线
                            self.receiveUser='所有人'
                        }
                        self.setHint(offlineName + "下线了");
                    } else if (obj.messageType == 3) {
                        var onlineName = obj.onlineUsers;
                        for (var i = 0; i < onlineName.length; i++) {
                            if (!(onlineName[i] == self.sendUser)) {//除了用户自己，其他用户都动态加载到侧边栏
                                self.navList.push({name:onlineName[i],navItem:onlineName[i]})
                            }
                        }
                        console.log("获取了在线的名单" + onlineName.toString());
                    } else {
                        self.setMessageInnerHTML(obj.fromusername + "对" + obj.tousername + "说：" + obj.textMessage);
                    }
                };

                //连接关闭的回调事件
                webSocket.onclose = function () {
                    console.log("连接已关闭...");
                    self.setHint("连接已经关闭....");
                };
            } else {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
            }
        },
        methods:{
            preText (pretext) {//文本域换行保留原格式
                return pretext.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, '&nbsp;')
            },
            changeReceiver(name){
                // alert(name)
                this.receiveUser=name
            },

            //将消息显示在网页上
            //收
            setMessageInnerHTML(innerHTML) {
                var receiveUser=this.receiveUser
                // document.getElementById('receive').innerHTML += '<span>'+innerHTML +'</span>' +'<br/>';
                document.getElementById('receiveTbody').innerHTML += '<tr><td class="receive">'+innerHTML+'</td></tr>';
            },

            //发
            sendMessage(innerHTML) {
                document.getElementById('receiveTbody').innerHTML += '<tr><td style="float: right">'+innerHTML+'</td></tr>';
            },

            setHint(innerHTML){
                this.$notify.info({
                    title: '提示',
                    message: ''+innerHTML,
                    duration: 20000
                });
                //  20s
            },

            closeWebSocket() {
                //直接关闭websocket的连接
                this.webSocket.close();
            },

            send() {
                this.remarks = this.preText(this.text);
                var selectText = this.receiveUser;//选择的接收方
                if (selectText == "所有人") {
                    selectText = "All";
                    this.sendMessage(this.sendUser + "对所有人说：" + this.remarks);
                } else {
                    // this.setMessageInnerHTML(this.sendUser + "对" + selectText + "说：" + this.text);
                    this.sendMessage(this.sendUser + "对" + selectText + "说：" + this.remarks);

                }
                var message = {
                    "message": this.remarks,
                    "username": this.sendUser,
                    "to": selectText
                };
                this.webSocket.send(JSON.stringify(message));
                this.text='';//发送完消息就清空
                this.remarks=''
            },
        }
    })
</script>
<style>
    html,body{
        margin: 0;
        padding: 0;
        height: 100%;
    }
    #app{
        height: 100%;
    }
    #nave,#side,#chat,#receive,#send{
        /*border: 1px solid red;*/
    }
    #nave{
        height: 7%;
        background-color: #EEE9E9;
    }
    #side{
        float: left;
        height: 93%;
        width: 15%;
        /*border-right: 1px solid gray;*/
        overflow: auto;
    }
    #chat{
        float: right;
        height: 93%;
        width: 84.7%;
    }
    #receive{
        height: 71%;
        border-bottom: 1px solid gray;
        overflow: auto;
    }
    #send{
        height: 28.9%;
        overflow: auto;
    }
   /* #receive span{
        display: inline-block;
        margin: 5px;
        padding: 5px;
        font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
        font-size: 17px;
        color: #c3790d;
        !*background-color: lightyellow;*!
        border: 2px solid #ED8D01;
        border-radius: 6px;
        box-shadow: 0 2px 12px 0 gray;
    }*/
    table tr{
        display: inline-block;
        width: 99%;
        height:auto;
        margin: 5px;
    }
    td{
        padding: 6px;
        font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
        font-size: 17px;
        color: #c3790d;
        /*background-color: lightyellow;*/
        border: 2px solid #ED8D01;
        border-radius: 6px;
        box-shadow: 0 2px 12px 0 gray;
    }
    .receive{
        color: black;
        background-color: #e5e5e5;
        border: none;
        box-shadow: 0 2px 12px 0 gray;
    }
</style>
</html>
